# coding: utf-8

from django.http import (
        HttpResponse, HttpResponseServerError, HttpResponseRedirect
    )
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from jd_oss.tools import *
from .asset_tools import *
from .models import AssetInfo
from .forms import AssetForm

# Create your views here.


@login_required
def asset_list(request):
    """
    资产列出
    """

    header_title, path1, path2 = u'资产管理', u'IT资产', u'查看资产'
    model_fields = get_modelfield('jd_asset', 'AssetInfo')
    export = request.GET.get("export", False)

    # 默认显示的字段
    exclude_field = ['it_id', 'it_detail']
    # 可手选显示的字段
    field_mapped = {k: v for k, v in get_modelfield(
        'jd_asset', 'AssetInfo').items() if k not in exclude_field}
    # 初始显示的字段 it_id 和 it_detail 默认已有这里不要写入
    default_display_field = ['it_serial', 'it_user', 'it_type', 'it_dep',
                             'it_size', 'it_status', 'it_brand', 'it_cost',
                             'it_reason', 'it_buytime',
                             'it_channel', 'it_dec']

    asset_find = search_asset(request)
    # 所有对象， 分页器， 本页对象， 所有页码， 本页页码，是否显示第一页，是否显示最后一页
    assets_list, p, assets, page_range, current_page, show_first, show_end = pages(asset_find, request)

    if export:
        s = write_excel(asset_find)
        if s[0]:
            file_name = s[1]
        smg = u'excel文件已生成，请点击下载!'
        return my_render('jasset/asset_excel_download.html', locals(), request)


    return my_render('jasset/asset_list.html', locals(), request)


@login_required
def asset_detail(request):
    """
    查看某个资产的所有详细信息
    """
    header_title, path1, path2 = u'主机详细信息', u'资产管理', u'资产详情'
    asset_id = request.GET.get('it_id', '')
    asset_info = AssetInfo.objects.get(it_id=asset_id)
    field_list = filter(lambda x: x.startswith('it_'), dir(asset_info))
    # 数据字段
    field_mapped = get_modelfield('jd_asset', 'AssetInfo')

    return my_render('jasset/asset_detail.html', locals(), request)


@login_required
def asset_del(request):
    """
    删除资产
    """
    asset_id = request.GET.get('it_id', '')
    if asset_id:
        Asset.objects.filter(it_id=asset_id).delete()

    if request.method == 'POST':
        asset_batch = request.GET.get('arg', '')
        asset_id_all = str(request.POST.get('asset_id_all', ''))

        if asset_batch:
            for asset_id in asset_id_all.split(','):
                asset = AssetInfo.objects.filter(it_id=asset_id)
                asset.delete()

    return HttpResponse(u'删除成功')


@login_required
def asset_add(request):
    """
    Asset add view
    添加资产
    """
    header_title, path1, path2 = u'添加资产', u'资产管理', u'添加资产'
    af = AssetForm()
    if request.method == 'POST':
        af_post = AssetForm(request.POST)
        it_serial = request.POST.get('it_serial', '')
        print it_serial
        try:
            if AssetInfo.objects.filter(it_serial=it_serial):
                error = u'资产 %s 已存在!' % it_serial
                raise ServerError(error)
        except ServerError:
            pass
        else:
            try:
                if af_post.is_valid():
                    # asset_save = af_post.save(commit=False)
                    af_post.save()
                    print af_post
                    # af_post.save_m2m()
                    msg = u'资产 %s 添加成功' % it_serial
                else:
                    esg = u'资产 %s 添加失败' % it_serial
            except Exception, e:
                print e
                esg = u"资产 %s 添加出错：\n %s" % (it_serial, e)
                return my_render('jasset/asset_add.html', locals(), request)
    return my_render('jasset/asset_add.html', locals(), request)


@login_required
def asset_edit(request):
    """
    修改资产信息
    """
    header_title, path1, path2 = u'添加资产', u'资产管理', u'修改资产'
    if request.method == 'GET':
        it_id = request.GET.get('it_id', '')
        asset = AssetInfo.objects.get(it_id=it_id)
        af = AssetForm(instance=asset)
        # 特殊处理部分
        it_status_index = [i[0]
                           for i in asset.ASSET_STATUS
                           if i[1] == asset.it_status][0]
        it_type_index = [i[0]
                         for i in asset.ASSET_TYPE if i[1] == asset.it_type][0]
        it_dep_index = [i[0]
                        for i in asset.ASSET_DEP if i[1] == asset.it_dep][0]
        it_user_index = [i[0]
                         for i in asset.ASSET_USER if i[1] == asset.it_user][0]
        it_usetime = asset.it_usetime
        it_buytime = asset.it_buytime
        return my_render('jasset/asset_edit.html', locals(), request)
    elif request.method == 'POST':
        af_post = AssetForm(request.POST)
        try:
            if af_post.is_valid():
                af_post.save()
                print af_post
                msg = u'资产 %s 修改成功' % it_serial
            else:
                esg = u'资产 %s 修改失败' % it_serial
        except Exception, e:
            esg = u"资产 %s 添加出错：\n %s" % (it_serial, e)
            return my_render('jasset/asset_edit.html', locals(), request)


@login_required
def asset_add_batch(request):
    """
    Upload asset excel file view
    """
    if request.method == 'POST':
        excel_file = request.FILES.get('file_name', '')
        ret = excel_to_db(excel_file)
        if ret:
            smg = u'批量添加成功'
        else:
            emg = u'批量添加失败,请检查格式.'
    return my_render('jasset/asset_add_batch.html', locals(), request)


@login_required
def asset_add_field(request):
    """
    ajax请求：
        添加可选字段
    """
    field_name = request.POST.get('field_name', '')
    field_value = request.POST.get('field_value', '')
    try:
        exist = AssetInfo.objects.get(**{field_name: field_value})
    except Exception, e:
        obj = AssetInfo.objects.create(**{field_name: field_value})
        return HttpResponse('')


@login_required
def asset_update(request):
    """
    批量更新功能
    """
    keyfield = request.GET.get('keyfield', '')
    keyword = request.GET.get('keyword', '').strip()
    model_fields = get_modelfield('jd_asset', 'AssetInfo')
    af = AssetForm()
    logger.debug(request.POST)
    if request.method == 'POST':
        change_dict = {k: v for k, v in request.POST.items()
                       if v and k.startswith('it_')
                       }
        asset_find = search_asset(request)

        for field in change_dict:
            asset_find.update(**change_dict)

        for asset in asset_find:
            logger.debug(asset_find)
            logger.debug(asset)
            # asset.save()

        return HttpResponseRedirect("%s?keyword=%s&keyfield=%s" % (
                                                reverse("asset_list"),
                                                keyword,
                                                keyfield
                                                ))
    return my_render('jasset/asset_update.html', locals(), request)


def get_role(request):
    pass
